package com.mx.zb.mng.ctrl;

import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.mx.zb.mng.bo.Template;
import com.mx.zb.mng.dao.TemplateMapper;
import com.mx.zb.mng.utils.AjaxResult;
import com.mx.zb.mng.utils.context.ContextThread;
import com.mx.zb.mng.utils.db2.Page;
import com.mx.zb.mng.utils.db2.PageHelper;
import com.mx.zb.mng.utils.ex.RestAnnotation;

@RestController
@RestAnnotation
@RequestMapping("/a/biz")
public class TemplateRestCtrl {
	
	@Autowired
	public TemplateMapper templateMapper;
	
	@RequestMapping(value = { "/tmp" })
	@ResponseBody
	public AjaxResult toTemplateList(Model model) {
		PageHelper.startPage();
		Page<Template> pnPages =templateMapper.findAll();
		return new AjaxResult().success(pnPages);
	}
	
	@RequestMapping(value = { "/tmp" }, method = {RequestMethod.DELETE})
	@ResponseBody
	public AjaxResult deleteTemplate( @RequestBody Template t) {
		templateMapper.deleteByPrimaryKey(t.getId());
		return new AjaxResult().success();
		
	}
	
	@RequestMapping(value = { "/tmp" }, method = {RequestMethod.PUT})
	@ResponseBody
	public AjaxResult addTemplate(@RequestBody Template t) {
		/* Pattern pattern = Pattern.compile("[0-9]*");
		boolean b=  pattern.matcher(t.getWxTemplateId()).matches();  
		if(!b) {
			throw new NumberFormatException();
		}*/
		t.setCreateDate(new Date());
		t.setCreateOper(ContextThread.get().getOperatorId());
		templateMapper.insert(t);
		return new AjaxResult().success();
	}
	
	@RequestMapping(value = { "/tmp/check" }, method = {RequestMethod.PUT})
	@ResponseBody
	public AjaxResult checkTemplate(@RequestBody JSONObject param) {
		String name = param.get("name").toString();
		Template t=new Template();
		t.setName(name);
	Page<Template> pTemp = 	 templateMapper.findByParams(t);
	if(pTemp!=null && pTemp.size()>0) {
		return new AjaxResult().failure();
	}
		return new AjaxResult().success();
	}

}
